//
//  DataBaseHandle.m
//  Share_Home_F
//
//  Created by dllo on 15/4/25.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "DataBaseHandle.h"

@implementation DataBaseHandle
+(instancetype)shareDataBaseHandle {
    static DataBaseHandle *dataBaseHandle = nil;
    static dispatch_once_t oneToTake;
    dispatch_once(&oneToTake, ^{
        dataBaseHandle = [[DataBaseHandle alloc] init];
    });
    return dataBaseHandle;
}

-(void)openDB {
    // 先获取沙盒路径
    NSArray *sandArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *sandBoxPath = [sandArr lastObject];
    // 拼接一个数据库的路径,如果这个路径下没有数据库则会创建一个数据库,并且打开这个数据库,如果有数据库了,则直接打开
    NSString *dbPath = [sandBoxPath stringByAppendingPathComponent:@"Special.sqlite"];
    int result = sqlite3_open([dbPath UTF8String], &dbPoint);
    if (result == SQLITE_OK) {
        NSLog(@"数据库开启成功");
        NSLog(@"%@", dbPath);
    }else {
        NSLog(@"数据库开启失败");
    }
}

-(void)createTable {
       NSString *sqlStr = @"create table if not exists special(number NSInteger primary key autoincrement,id text, introduction text, keyword text, pic text, title text)";
    int result = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
    if (result == SQLITE_OK) {
        NSLog(@"创建表成功");
    } else {
        NSLog(@"创建表失败");
    }
}

-(void)insertSql:(Sqlite *)special {
    NSString *insertSql = [NSString stringWithFormat:@"insert into special(id, introduction, keyword, pic, title) values ('%@', '%@', '%@', '%@', '%@')", special.id, special.introduction, special.keyword, special.pic, special.title];
    int result = sqlite3_exec(dbPoint, [insertSql UTF8String], nil, nil, nil);
    if (result == SQLITE_OK) {
        NSLog(@"插入对象成功");
    } else {
        NSLog(@"插入对象失败");
    }
}


-(void)deleteSql:(NSString *)id {
    
    NSString *deleteSql = [NSString stringWithFormat:@"delete from special where id = %@", id];
    int result = sqlite3_exec(dbPoint, [deleteSql UTF8String], nil, nil, nil);
    if (result == SQLITE_OK) {
        NSLog(@"删除对象成功");
    } else {
        NSLog(@"删除对象失败");
    }
}


-(void)closeDB {
    int result = sqlite3_close(dbPoint);
    if (result == SQLITE_OK) {
        NSLog(@"关闭数据库成功");
    }else {
        NSLog(@"关闭数据库失败");
    }
}

@end
